package XishiBackend.controllers.android;

import java.util.*;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import XishiBackend.base.Constant;
import XishiBackend.base.Json;
import XishiBackend.base.TimeUtil;
import XishiBackend.base.Web;
import XishiBackend.models.entity.Order;
import XishiBackend.models.entity.User;
import XishiBackend.services.android.AndroidOrderService;

@RestController
@EnableAutoConfiguration
@RequestMapping("/android/order")
public class AndroidOrderController {
    @Autowired
    private AndroidOrderService oS;
    
    @RequestMapping(value = "/orderdetail", method = RequestMethod.POST)
    public String orderdetail(@RequestParam("sig") String sig,@RequestParam("orderId") long orderId) {
        if(oS.findOne(orderId) == null) {
            return Json.format(1, "获取订单详情失败，订单不存在");
        }
        Map<String, Object> r = oS.detail(orderId);
        return Json.format(0, "获取订单详情成功", r);
    }
    
    @RequestMapping(value = "/dishesdetail", method = RequestMethod.POST)
    public String dishesdetail(@RequestParam("sig") String sig,@RequestParam("dishesId") long dishesId) {
        Map<String, Object> r = oS.findDishesById(dishesId);
        if(r == null) {
            return Json.format(1, "获取菜品详情失败，菜品不存在");
        }
        else {
            return Json.format(0, "获取菜品详情成功", r);
        }
    }
    
    @RequestMapping(value = "/orderlist", method=RequestMethod.POST)
    public String orderlist(@RequestParam("sig") String sig,@RequestParam("restaurantId") long restaurantId,@RequestParam("time") String time) {
        List<Map<String, Object>> list = oS.findOrderListWithAllStatus(restaurantId, time);
        if(list == null) {
            return Json.format(1, "获取订单列表失败，店铺不存在");
        }
        Map<String, Object> r = new HashMap<String, Object>();
        r.put("orderList", list);
        r.put("time", TimeUtil.now());
        return Json.format(0, "获取订单列表成功", r);
    }
    
    @RequestMapping(value = "/neworderlist", method=RequestMethod.POST)
    public String neworderlist(@RequestParam("sig") String sig,@RequestParam("restaurantId") long restaurantId, @RequestParam("time") String time) {
        List<Map<String, Object>> list = oS.findOrderList(Constant.NEW, restaurantId, time);
        if(list == null) {
            return Json.format(1, "获取新订单列表失败，店铺不存在");
        }
        Map<String, Object> r = new HashMap<String, Object>();
        r.put("orderList", list);
        r.put("time", TimeUtil.now());
        return Json.format(0, "获取新订单列表成功", r);
    }
    
    @RequestMapping(value = "/deliveryorderlist", method=RequestMethod.POST)
    public String deliveryorderlist(@RequestParam("sig") String sig,@RequestParam("restaurantId") long restaurantId, @RequestParam("time") String time) {
        List<Map<String, Object>> list = oS.findOrderList(Constant.DELIVERY, restaurantId, time);
        if(list == null) {
            return Json.format(1, "获取配送订单列表失败，店铺不存在");
        }
        Map<String, Object> r = new HashMap<String, Object>();
        r.put("orderList", list);
        r.put("time", TimeUtil.now());
        return Json.format(0, "获取配送订单列表成功", r);
    }
    
    @RequestMapping(value = "/completeorderlist", method=RequestMethod.POST)
    public String completeorderlist(@RequestParam("sig") String sig,@RequestParam("restaurantId") long restaurantId, @RequestParam("time") String time) {
        List<Map<String, Object>> list = oS.findOrderList(Constant.COMPLETE, restaurantId, time);
        if(list == null) {
            return Json.format(1, "获取配送订单列表失败，店铺不存在");
        }
        Map<String, Object> r = new HashMap<String, Object>();
        r.put("orderList", list);
        r.put("time", TimeUtil.now());
        return Json.format(0, "获取完成订单列表成功", r);
    }
    
    @RequestMapping(value = "/cancelorderlist", method=RequestMethod.POST)
    public String cancelorderlist(@RequestParam("sig") String sig,@RequestParam("restaurantId") long restaurantId, @RequestParam("time") String time) {
        List<Map<String, Object>> list = oS.findOrderList(Constant.CANCEL, restaurantId, time);
        if(list == null) {
            return Json.format(1, "获取配送订单列表失败，店铺不存在");
        }
        Map<String, Object> r = new HashMap<String, Object>();
        r.put("orderList", list);
        r.put("time", TimeUtil.now());
        return Json.format(0, "获取取消订单列表成功", r);
    }
    
    @RequestMapping(value = "/order2new", method=RequestMethod.POST)
    public String order2new(@RequestParam("sig") String sig,@RequestParam("orderId") long orderId, @RequestParam("adminId") long adminId) {
        Order o = oS.findOne(orderId);
        if(o == null) {
            return Json.format(1, "订单置为新订单失败，订单不存在");
        }
        if(!oS.existOperator(adminId)) {
            return Json.format(3, "订单置为新订单失败，操作员不存在");
        }
        
        String now = TimeUtil.now();
        o.setStatus(Constant.NEW);
        o.setUpdateTime(now);
        o.setOperatorId(adminId);
        if(oS.save(o)) {
            return Json.format(0, "订单置为新订单成功");
        }
        else {
            return Json.format(2, "订单置为新订单失败");
        }
    }
    
    @RequestMapping(value = "/order2delivery", method=RequestMethod.POST)
    public String order2delivery(@RequestParam("sig") String sig,@RequestParam("orderId") long orderId, @RequestParam("adminId") long adminId) {
        Order o = oS.findOne(orderId);
        if(o == null) {
            return Json.format(1, "订单置为配送订单失败，订单不存在");
        }
        if(!oS.existOperator(adminId)) {
            return Json.format(3, "订单置为配送订单失败，操作员不存在");
        }
        
        String now = TimeUtil.now();
        o.setStatus(Constant.DELIVERY);
        o.setUpdateTime(now);
        o.setOperatorId(adminId);
        if(oS.save(o)) {
            //String ret = sendWxMessage(o);
            String ret = sendWxCustomMessage(o);
            if(!ret.equals("success")) {
                System.out.println("消息推送失败。orderId:"+o.getOrderId()+",msg:"+ret);
            }
            return Json.format(0, "订单置为配送订单成功");
        }
        else {
            return Json.format(2, "订单置为配送订单失败");
        }
    }
    
    @RequestMapping(value = "/order2complete", method=RequestMethod.POST)
    public String order2complete(@RequestParam("sig") String sig,@RequestParam("orderId") long orderId, @RequestParam("adminId") long adminId) {
        Order o = oS.findOne(orderId);
        if(o == null) {
            return Json.format(1, "订单置为完成订单失败，订单不存在");
        }
        if(!oS.existOperator(adminId)) {
            return Json.format(3, "订单置为完成订单失败，操作员不存在");
        }
        
        String now = TimeUtil.now();
        o.setStatus(Constant.COMPLETE);
        o.setUpdateTime(now);
        o.setOperatorId(adminId);
        if(oS.save(o)) {
            return Json.format(0, "订单置为完成订单成功");
        }
        else {
            return Json.format(2, "订单置为完成订单失败");
        }
    }
    
    @RequestMapping(value = "/order2cancel", method=RequestMethod.POST)
    public String order2cancel(@RequestParam("sig") String sig,@RequestParam("orderId") long orderId, @RequestParam("adminId") long adminId) {
        Order o = oS.findOne(orderId);
        if(o == null) {
            return Json.format(1, "订单置为取消订单失败，订单不存在");
        }
        if(!oS.existOperator(adminId)) {
            return Json.format(3, "订单置为取消订单失败，操作员不存在");
        }
        
        String now = TimeUtil.now();
        o.setStatus(Constant.CANCEL);
        o.setUpdateTime(now);
        o.setOperatorId(adminId);
        o.setCancelRemark(Constant.MANAGER_CANCEL);
//        if(o.getOrderType() == Constant.WX_ONLINE && o.isHasPaid() == Constant.NOT_PAID) {
//            //如果是没有付过款的微信订单，就调用关闭订单接口
//            String resp = Constant.wxCloseOrder(o);
//            JSONObject json = JSONObject.fromObject(resp);
//            if(!json.getString("return_code").equals("SUCCESS")) {
//                System.out.println(json.getString("return_msg")+":"+o.getOrderId());
//            }
//        }
        if(oS.save(o)) {
            return Json.format(0, "订单置为取消订单成功");
        }
        else {
            return Json.format(2, "订单置为取消订单失败");
        }
    }
    
    private String sendWxMessage(Order o) {
        Map<String,Object> m = oS.orderOptimization(o);
        String dishes = "";
        for(Map<String, Object> d : (List<Map<String, Object>>)m.get("dishes")) {
            dishes += d.get("name") + ":" + d.get("count") + "份 ";
        }
        String accessToken = Constant.wxGetAccessToken();
        String url = Constant.W_SEND + accessToken,
               templateId = Constant.W_MESSAGE_TEMPLATE_ID[1];
        User u = oS.findUserByUserId(o.getUserId());
        String remark = "请稍后至取餐点领取您的美味。";
        if(o.getOrderType() == Constant.COD) {
            remark += "您的订单需要货到付款，请准备好相应零钱："+o.getTotalPrice()+"元。";
        }
        //参数
        JSONObject param = new JSONObject();
        param.put("touser", u.getOpenId());
        param.put("template_id", templateId);
        param.put("url", "http://weixin.qq.com/download");
        param.put("topcolor", "#FF0000");
        param.put("data", new JSONObject());
        param.getJSONObject("data").put("first", new JSONObject());
        param.getJSONObject("data").getJSONObject("first").put("value", "手机号"+u.getTel()+"的订单已处于配送状态");
        param.getJSONObject("data").getJSONObject("first").put("color", "#173177");
        param.getJSONObject("data").put("keyword1", new JSONObject());
        param.getJSONObject("data").getJSONObject("keyword1").put("value", m.get("takeNo"));
        param.getJSONObject("data").getJSONObject("keyword1").put("color", "#173177");
        param.getJSONObject("data").put("keyword2", new JSONObject());
        param.getJSONObject("data").getJSONObject("keyword2").put("value", dishes);
        param.getJSONObject("data").getJSONObject("keyword2").put("color", "#173177");
        param.getJSONObject("data").put("remark", new JSONObject());
        param.getJSONObject("data").getJSONObject("remark").put("value", remark);
        param.getJSONObject("data").getJSONObject("remark").put("color", "#173177");
        JSONObject json = JSONObject.fromObject(Web.sendPost(url,  new HashMap<String, String>(), param.toString()));
        if(json.getInt("errcode") != 0) {
            return json.getString("errmsg");
        }
        return "success";
    }
    
    private String sendWxCustomMessage(Order o) {
        Map<String,Object> m = oS.orderOptimization(o);
        String dishes = "";
        for(Map<String, Object> d : (List<Map<String, Object>>)m.get("dishes")) {
            dishes += d.get("name") + ":" + d.get("count") + "份 ";
        }
        String accessToken = Constant.wxGetAccessToken();
        String url = Constant.W_CUSTEM_SEND + accessToken;
        User u = oS.findUserByUserId(o.getUserId());
        String remark = "请尽快至取餐点领取您的美味。";
        if(o.getOrderType() == Constant.COD) {
            remark += "您的订单需要货到付款，请准备好相应零钱："+o.getTotalPrice()+"元。";
        }
        
        String content = "您好，您的订单已配送至取餐点，订单信息如下：\n"+
                "手机号："+u.getTel()+"\n"+
                "下单时间："+o.getCreateTime()+"\n"+
                "取餐号："+m.get("takeNo")+"\n"+
                "菜品："+dishes+"\n"+
                "取餐地址："+oS.findDistributionById(o.getDistributionId()).getAddress()+"\n"+
                remark;

        //参数
        JSONObject param = new JSONObject();
        param.put("touser", u.getOpenId());
        param.put("msgtype", "text");
        param.put("text", new JSONObject());
        param.getJSONObject("text").put("content", content);

        JSONObject json = JSONObject.fromObject(Web.sendPost(url,  new HashMap<String, String>(), param.toString()));
        if(json.getInt("errcode") != 0) {
            return json.getString("errmsg");
        }
        return "success";
    }
}
